package org.wu.framework.authorization.platform.infrastructure.persistence;

import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.wu.framework.authorization.annotation.RequiredAuthorization;
import org.wu.framework.authorization.platform.application.dto.SysPermissionDTO;
import org.wu.framework.authorization.platform.infrastructure.entity.SysPermissionDO;
import org.wu.framework.authorization.platform.infrastructure.converter.SysPermissionConverter;
import org.wu.framework.authorization.platform.infrastructure.mapper.SysPermissionMapper;
import org.wu.framework.authorization.platform.domain.model.sys.permission.SysPermissionRepository;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import org.wu.framework.core.NormalUsedString;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import jakarta.annotation.Resource;
import org.wu.framework.authorization.platform.domain.model.sys.permission.SysPermission;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;

import java.util.List;

import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;

/**
 * describe 系统权限
 *
 * @author Jia wei Wu
 * @date 2025/08/03 01:55 下午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Repository
public class SysPermissionRepositoryImpl implements SysPermissionRepository {

    @Resource
    LazyLambdaStream lazyLambdaStream;
    @Resource
    ApplicationContext applicationContext;

    /**
     * describe 新增系统权限
     *
     * @param sysPermission 新增系统权限
     * @return {@link Result<SysPermission>} 系统权限新增后领域对象
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<SysPermission> story(SysPermission sysPermission) {

        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        if(ObjectUtils.isEmpty(sysPermissionDO.getId()))
        {
            sysPermissionDO.setId(sysPermissionDO.getUrl()+ NormalUsedString.UNDERSCORE+sysPermissionDO.getMethod());
        }
        lazyLambdaStream.upsert(sysPermissionDO);
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增系统权限
     *
     * @param sysPermissionList 批量新增系统权限
     * @return {@link Result<List<SysPermission>>} 系统权限新增后领域对象集合
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<List<SysPermission>> batchStory(List<SysPermission> sysPermissionList) {
        List<SysPermissionDO> sysPermissionDOList = sysPermissionList.stream().map(sysPermission -> {
            SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
            if(ObjectUtils.isEmpty(sysPermissionDO.getId()))
            {
                sysPermissionDO.setId(sysPermissionDO.getUrl()+ NormalUsedString.UNDERSCORE+sysPermissionDO.getMethod());
            }
            return sysPermissionDO;
        }).collect(Collectors.toList());
        lazyLambdaStream.upsert(sysPermissionDOList);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个系统权限
     *
     * @param sysPermission 查询单个系统权限
     * @return {@link Result<SysPermission>} 系统权限领域对象
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<SysPermission> findOne(SysPermission sysPermission) {
        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        SysPermission sysPermissionOne = lazyLambdaStream.selectOne(
                LazyWrappers.<SysPermissionDO>lambdaWrapper()
                        .eqIgnoreEmpty(SysPermissionDO::getCreateTime, sysPermissionDO.getCreateTime())
                        .eqIgnoreEmpty(SysPermissionDO::getId, sysPermissionDO.getId())
                        .eqIgnoreEmpty(SysPermissionDO::getIsDeleted, false)
                        .eqIgnoreEmpty(SysPermissionDO::getMethod, sysPermissionDO.getMethod())
                        .eqIgnoreEmpty(SysPermissionDO::getUrl, sysPermissionDO.getUrl())
                        .eqIgnoreEmpty(SysPermissionDO::getZoneId, sysPermissionDO.getZoneId())
                , SysPermission.class);
        return ResultFactory.successOf(sysPermissionOne);
    }

    /**
     * describe 查询多个系统权限
     *
     * @param sysPermission 查询多个系统权限
     * @return {@link Result<List<SysPermission>>} 系统权限领域对象
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<List<SysPermission>> findList(SysPermission sysPermission) {
        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        List<SysPermission> sysPermissionList = lazyLambdaStream.selectList(
                LazyWrappers.<SysPermissionDO>lambdaWrapper()
                        .eqIgnoreEmpty(SysPermissionDO::getCreateTime, sysPermissionDO.getCreateTime())
                        .eqIgnoreEmpty(SysPermissionDO::getId, sysPermissionDO.getId())
                        .eqIgnoreEmpty(SysPermissionDO::getIsDeleted, false)
                        .eqIgnoreEmpty(SysPermissionDO::getMethod, sysPermissionDO.getMethod())
                        .eqIgnoreEmpty(SysPermissionDO::getUrl, sysPermissionDO.getUrl())
                        .eqIgnoreEmpty(SysPermissionDO::getZoneId, sysPermissionDO.getZoneId())
                , SysPermission.class);
        return ResultFactory.successOf(sysPermissionList);
    }

    public Result<List<SysPermissionDTO>> findScanPermission() {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RequestMapping.class);

        List<SysPermissionDTO> sysPermissionDTOList = new ArrayList<>();

        beansWithAnnotation.values()
                .stream()
                .map(Object::getClass)
                .filter(clazz -> AnnotatedElementUtils.getMergedAnnotation(clazz, RequestMapping.class) != null)
                .forEach(interfaceProviderClass -> {
                    RequestMapping mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(interfaceProviderClass, RequestMapping.class);
                    String[] parentPath = mergedAnnotation.value();
                    if (AnnotatedElementUtils.hasAnnotation(interfaceProviderClass, RequiredAuthorization.class)) {

                        for (String path : parentPath) {
                            for (RequestMethod method : RequestMethod.values()) {
                                SysPermissionDTO sysPermissionDTO = new SysPermissionDTO();
                                sysPermissionDTO.setUrl(path);
                                sysPermissionDTO.setMethod(method.name());
                                sysPermissionDTO.setIsDeleted(false);
                                sysPermissionDTO.setCreateTime(LocalDateTime.now());
                                sysPermissionDTOList.add(sysPermissionDTO);

                            }
                        }
                        return;
                    } else {


                        Method[] methods = interfaceProviderClass.getMethods();

                        for (Method method : methods) {
                            boolean hasRequestMapping = AnnotatedElementUtils.hasAnnotation(method, RequestMapping.class);
                            boolean hasRequiredAuthorization = AnnotatedElementUtils.hasAnnotation(method, RequiredAuthorization.class);
                            if (hasRequestMapping && hasRequiredAuthorization) {
                                RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
                                for (String path : requestMapping.path()) {
                                    List<RequestMethod> requestMethodList = new ArrayList<>();


                                    if (ObjectUtils.isEmpty(requestMapping.method())) {
                                        requestMethodList = Arrays.stream(RequestMethod.values()).toList();
                                    } else {
                                        requestMethodList = Arrays.stream(requestMapping.method()).toList();
                                    }
                                    for (RequestMethod requestMethod : requestMethodList) {
                                        SysPermissionDTO sysPermissionDTO = new SysPermissionDTO();
                                        sysPermissionDTO.setUrl(path);
                                        sysPermissionDTO.setMethod(requestMethod.name());
                                        sysPermissionDTO.setIsDeleted(false);
                                        sysPermissionDTO.setCreateTime(LocalDateTime.now());
                                        sysPermissionDTOList.add(sysPermissionDTO);
                                    }
                                }

                            }
                        }
                    }
                });
        return ResultFactory.successOf(sysPermissionDTOList);
    }

    /**
     * describe 分页查询多个系统权限
     *
     * @param size          当前页数
     * @param current       当前页
     * @param sysPermission 分页查询多个系统权限
     * @return {@link Result<LazyPage<SysPermission>>} 分页系统权限领域对象
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<LazyPage<SysPermission>> findPage(int size, int current, SysPermission sysPermission) {
        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        LazyPage<SysPermission> lazyPage = new LazyPage<>(current, size);
        LazyPage<SysPermission> sysPermissionLazyPage = lazyLambdaStream.selectPage(
                LazyWrappers.<SysPermissionDO>lambdaWrapper()
                        .eqIgnoreEmpty(SysPermissionDO::getCreateTime, sysPermissionDO.getCreateTime())
                        .eqIgnoreEmpty(SysPermissionDO::getId, sysPermissionDO.getId())
                        .eqIgnoreEmpty(SysPermissionDO::getIsDeleted, false)
                        .eqIgnoreEmpty(SysPermissionDO::getMethod, sysPermissionDO.getMethod())
                        .eqIgnoreEmpty(SysPermissionDO::getUrl, sysPermissionDO.getUrl())
                        .eqIgnoreEmpty(SysPermissionDO::getZoneId, sysPermissionDO.getZoneId())
                , lazyPage, SysPermission.class);
        return ResultFactory.successOf(sysPermissionLazyPage);
    }

    /**
     * describe 删除系统权限
     *
     * @param sysPermission 删除系统权限
     * @return {@link Result<SysPermission>} 系统权限
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<SysPermission> remove(SysPermission sysPermission) {
        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        lazyLambdaStream.delete(
                LazyWrappers.<SysPermissionDO>lambdaWrapper()
                        .eqIgnoreEmpty(SysPermissionDO::getCreateTime, sysPermissionDO.getCreateTime())
                        .eqIgnoreEmpty(SysPermissionDO::getId, sysPermissionDO.getId())
                        .eqIgnoreEmpty(SysPermissionDO::getIsDeleted, false)
                        .eqIgnoreEmpty(SysPermissionDO::getMethod, sysPermissionDO.getMethod())
                        .eqIgnoreEmpty(SysPermissionDO::getUrl, sysPermissionDO.getUrl())
                        .eqIgnoreEmpty(SysPermissionDO::getZoneId, sysPermissionDO.getZoneId())
        );
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在系统权限
     *
     * @param sysPermission 系统权限领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2025/08/03 01:55 下午
     **/

    @Override
    public Result<Boolean> exists(SysPermission sysPermission) {
        SysPermissionDO sysPermissionDO = SysPermissionConverter.INSTANCE.fromSysPermission(sysPermission);
        Boolean exists = lazyLambdaStream.exists(
                LazyWrappers.<SysPermissionDO>lambdaWrapper()
                        .eqIgnoreEmpty(SysPermissionDO::getCreateTime, sysPermissionDO.getCreateTime())
                        .eqIgnoreEmpty(SysPermissionDO::getId, sysPermissionDO.getId())
                        .eqIgnoreEmpty(SysPermissionDO::getIsDeleted, false)
                        .eqIgnoreEmpty(SysPermissionDO::getMethod, sysPermissionDO.getMethod())
                        .eqIgnoreEmpty(SysPermissionDO::getUrl, sysPermissionDO.getUrl())
                        .eqIgnoreEmpty(SysPermissionDO::getZoneId, sysPermissionDO.getZoneId())
        );
        return ResultFactory.successOf(exists);
    }

}